package three;
import java.util.*;

public class A059 {

    boolean[][] check;
    int m,n;
    int[] dx = {1,-1,0,0};
    int[] dy = {0,0,1,-1};
    public boolean exist(char[][] board, String word) {
        m = board.length;n = board[0].length;
        check = new boolean[m][n];
        char[] str = word.toCharArray();
        for(int i=0;i<m;i++) {
            for(int j=0;j<n;j++) {
                if(board[i][j]==str[0]) { //从第一个字符开始
                    check[i][j]=true;
                    boolean bool = dfs(board,str,1,i,j);
                    if(bool) return true;
                    //回溯
                    check[i][j]=false;
                }
            }
        }
        return false;
    }
    public boolean dfs(char[][] board,char[] str,int pos,int i,int j) {
        if(pos>=str.length) {
            return true;
        }
        //1.收集
        for(int k=0;k<4;k++) {
            int x = dx[k]+i;
            int y = dy[k]+j;
            if(x>=0&&x<m&&y>=0&&y<n && !check[x][y] && board[x][y]==str[pos]) {
                check[x][y]=true;
                boolean bool = dfs(board,str,pos+1,x,y);
                if(bool) return true;
                check[x][y]=false;
            }
        }
        return false;
    }
}
